<!--
 * @Author       : wfl
 * @LastEditors: qiye
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-05-04 17:28:32
 * @LastEditTime: 2023-08-07 16:53:39
-->
<script lang="ts" setup name="ValidateModal">
import { CircleCheck, Warning } from '@element-plus/icons-vue'

const props = defineProps({
  // 是否显示验证模式或校验码页面的显示选项
  showValidate: {
    type: Boolean,
    default: false
  },
  errorMap: {
    type: Map,
    default: () => new Map()
  },
  formValid: {
    type: Object,
    default: () => {}
  },
  flowValid: {
    type: Object,
    default: () => {}
  },
  designValid: {
    type: Object,
    default: () => {}
  },
  loadingPublish: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['close', 'publish'])

const loading = ref(false)
const loadingText = ref('正在检查基础信息...')
const activeTab = ref(0)
const isShow = computed(() => props.showValidate)
const errorList: Ref<Array<any>> = ref([])
const hasError = ref(false)
const status: Ref<'' | 'wait' | 'success' | 'error' | 'finish' | 'process' | undefined | any> = ref('wait')

// 重置状态
const resetStatus = () => {
  errorList.value = []
  status.value = 'process'
  hasError.value = false
}

// 等待校验过程，可根据实际情况修改等待时间
const sleep = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true)
    }, 1000)
  })
}

const setLoadingText = (text: string) => {
  document.getElementsByClassName('el-loading-text')[0].innerHTML = text
}

// 检验高级设置
const validateAdvance = async () => {
  setLoadingText('正在检高级设置...')
  await sleep()
  activeTab.value = 3
  status.value = 'success'
  loading.value = false
  setLoadingText('正在检查基础信息...')
}
// 检验流程设计
const validateFlow = async () => {
  resetStatus()
  const error = props.flowValid.validate()
  setLoadingText('正在检查流程设计...')
  activeTab.value = 2
  await sleep()
  if (error.length) {
    status.value = 'error'
    loading.value = false
    hasError.value = true
    errorList.value = error.map((v: string) => {
      return {
        message: v
      }
    })
  }
  else {
    validateAdvance()
  }
}

// 检验表单设计
const validateDesignForm = async () => {
  resetStatus()
  activeTab.value = 1
  setLoadingText('正在检查表单设计...')
  try {
    await sleep()
    const { widgetList } = props?.designValid?.getFormJson()
    if (!widgetList.length) {
      loading.value = false
      status.value = 'error'
      hasError.value = true
      errorList.value = [
        {
          message: '表单为空，请在【表单设计】中添加组件'
        }
      ]
      return
    }
    validateFlow()
  }
  catch (error) {
    validateFlow()
  }
}

// 检验基础设置
const validate = async () => {
  resetStatus()
  loading.value = true
  activeTab.value = 0
  await sleep()
  props.formValid.validate((valid: boolean, errors: Array<any>) => {
    if (valid) {
      validateDesignForm()
      status.value = 'success'
      return
    }
    loading.value = false
    hasError.value = true
    status.value = 'error'
    errorList.value = Object.keys(errors).map((v: any) => {
      const obj = errors[v][0]
      return {
        ...obj,
        message: `${obj.message.substring(3)}未设置`
      }
    })
  })
}

const errLen = computed(() => errorList.value.length)

const handReset = () => {
  errorList.value = []
  loading.value = false
  activeTab.value = 0
  loadingText.value = '正在检查基础信息...'
}
/**
 * @description: 关闭 or 关闭并发布
 * @param {*} flag true 仅关闭
 * @return {*}
 */
const toEditConfig = () => {
  if (!errLen.value) {
    emit('publish')
    loadingText.value = '正在发布...'
  }
  else {
    emit('close')
    handReset()
  }
}
watch(() => props.loadingPublish, val => {
  if (!val && !errLen.value)
    handReset()
})
// 关闭
const handleClose = () => {
  emit('close')
  handReset()
}
</script>

<template>
  <el-dialog
    v-model="isShow"
    draggable
    title="流程设置检验"
    width="800px"
    @opened="validate"
    @close="handleClose"
  >
    <el-steps
      :active="activeTab"
      :process-status="status"
      finish-status="success"
      align-center
    >
      <el-step
        title="基础设置"
        :status="activeTab === 0 && hasError ? 'error' : ''"
      />
      <el-step
        title="表单设计"
        :status="activeTab === 1 && hasError ? 'error' : ''"
      />
      <el-step
        title="流程设计"
        :status="activeTab === 2 && hasError ? 'error' : ''"
      />
      <el-step
        title="高级设置"
        :status="activeTab === 3 && hasError ? 'error' : ''"
      />
    </el-steps>
    <div
      v-loading="loading || (loadingPublish && !errLen)"
      class="iflow-warning-box"
      :element-loading-text="loadingText"
    >
      <template v-if="!loading && !(loadingPublish && !errLen)">
        <el-icon v-if="hasError" class="warning">
          <Warning />
        </el-icon>
        <el-icon v-else class="success">
          <CircleCheck />
        </el-icon>
        <p v-show="!loading">
          检验{{ errLen ? '失败' : '成功' }}
          <template v-if="errLen"> （{{ errLen }}处错误） </template>
        </p>
        <template v-for="(err, index) in errorList" :key="index">
          <el-alert
            class="ikflow-error-msg"
            :title="err.message"
            type="info"
            :closable="false"
          />
        </template>
        <el-button
          type="primary"
          class="w-full mt-[28px]"
          @click="toEditConfig"
        >
          {{ errLen ? '去修改' : '发布' }}
        </el-button>
      </template>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-step__head.is-success) {
  .el-step__line {
    background-color: var(--el-color-success);
  }
}

.iflow-warning-box {
  min-height: 300px;
  display: flex;
  align-items: center;
  flex-direction: column;
  padding: 48px 150px 32px;
  box-sizing: border-box;
  justify-content: center;

  p {
    font-size: 20px;
    margin-bottom: 16px;
  }

  .el-icon {
    font-size: 50px;
    margin-bottom: 8px;

    &.warning {
      color: var(--el-color-warning);
    }

    &.success {
      color: var(--el-color-success);
    }
  }

  .ikflow-error-msg {
    margin-bottom: 8px;
  }
}
</style>
